import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.justtest.FirstServiceGrpc;
import io.grpc.justtest.TestRequest;
import io.grpc.justtest.TestResponse;
import io.grpc.stub.StreamObserver;

import java.io.IOException;

public class TestServer {

    // 定义端口
    private final int port = 9527;
    // 服务
    private Server server;

    // 启动服务,并且接受请求
    private void start() throws IOException {

        server = ServerBuilder.forPort(port)
                .addService(new FirstImpl())
                .build()
                .start();
        System.out.println("服务开始启动-------端口：" + port);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                System.err.println("------shutting down gRPC server since JVM is shutting down-------");
                TestServer.this.stop();
                System.err.println("------server shut down------");
            }
        });
    }

    // stop服务
    private void stop() {
        if (server != null) {
            server.shutdown();
        }
    }

    // server阻塞到程序退出
    private void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }

    // 实现服务接口的类
    private class FirstImpl extends FirstServiceGrpc.FirstServiceImplBase {
        public void testgRPC(TestRequest request, StreamObserver<TestResponse> responseObserver) {
            int res = myAdd(request.getNum1(), request.getNum2());
            TestResponse build = TestResponse.newBuilder().setRes(res).build();
            // onNext()方法向客户端返回结果
            responseObserver.onNext(build);
            // 告诉客户端这次调用已经完成
            responseObserver.onCompleted();
        }

        /**
         * @Description: 加法实现
         * @create: 2021-01-29 15:01:51
         * @author:wwz
         */
        private int myAdd(int num1, int num2) {
            int res = num1 + num2;
            return res;
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        final TestServer server = new TestServer();
        server.start();
        server.blockUntilShutdown();
    }
}
